#-------------------------------------------------------------------------------
# By Daoyu @2010-10-07
#-------------------------------------------------------------------------------

from django.shortcuts import render_to_response
from django.http import HttpResponse, HttpResponseRedirect
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from django.template import RequestContext

from django.db.models import Q

from uncle.project.models import *
from uncle.users.models import *
from uncle.util.page import *
from uncle.util.util import *
from uncle.users.views import get_all_cat_skill_tool_tag

#-------------------------------------------------------------------------------
# Using the safe url view the project page, doesn't require log in.
#-------------------------------------------------------------------------------
def view_safe_url(request, p_id, safe_url):
    psu = Project_safe_url.objects.filter(project__id=p_id)
    email = Project_client_email.objects.filter(project__id=p_id)
    if psu:
        if psu[0].url == safe_url:
            from datetime import date, datetime
            today = date(datetime.now().year,datetime.now().month,datetime.now().day)            
            if psu[0].expire < today:
                return HttpResponseRedirect('/403/?msg=This URL expires!');
        else:
            return HttpResponseRedirect('/403/?msg=Wrong safe URL!');
    else:
        return HttpResponseRedirect('/403/?msg=Project does not exist!');
    
    obj = Project.objects.filter(id = p_id)
    if not obj:
        return HttpResponseRedirect('/403/?msg=Project does not exist!')

    

    pces = Project_client_email.objects.filter(project__id=p_id)

    pas = split_into_lists(
        [x for x in Project_artist.objects.filter(project__id = p_id)], count = 6)
    pys = split_into_lists(
        [x for x in Project_youtube.objects.filter(project__id = p_id, show__exact=True)], count = 6)
    pfs = split_into_lists(Project_file.objects.filter(project__id = p_id, show__exact=True), count = 6)
    pces = Project_client_email.objects.filter(project__id = p_id)

    pv = None  # the current project's playing film.
    if request.GET.has_key('m'):
        pf = Project_file.objects.filter(id = request.GET['m'])
        if pf:
            pv = pf[0].file
    elif request.GET.has_key('a'):
        pv = request.GET['a']
    else:
        _pv = Project_video.objects.filter(project__id = p_id)
        if _pv:
            pv = _pv[0].film

    return render_to_response('project/detail.html',
        {'project':obj[0], 'pass':pas, 'pfss':pfs,      # Kalle: changed: 'pass':pas, 'pfss':pfs,
         'pces':pces, 'pv':pv, 'pys':pys,'pces':pces,'email':email, },
        context_instance = RequestContext(request))    

#-------------------------------------------------------------------------------
# Set the expire date of safe url.
# If the first time view it, automatically set the expire to today.
#-------------------------------------------------------------------------------
@login_required
def safe_url(request, p_id):
    if not request.user.has_perm('users.is_producer'):
        return HttpResponseRedirect('/403/?msg=You do not have permission to view this page')
    if request.method=='GET':
        pro = Project.objects.get(id=p_id)
        email = Project_client_email.objects.filter(project__id=p_id)
        su = Project_safe_url()
        
        _su = Project_safe_url.objects.filter(project__id=p_id)
        
        if _su:
            su = _su[0]
        else:
            su.project = pro
            
            import random
            url = []
            for i in range(0,20):
                url.append(random.choice('abcdefghijklmnopqrstuvwxyz_'))

            su.url = ''.join(url)
            su.save()
    elif request.method=='POST':
        _su = Project_safe_url.objects.filter(project__id=p_id)
        if _su:
            _su[0].expire = request.POST['expire']
            _su[0].save()
        
        return HttpResponseRedirect('/project/'+str(p_id)+'/safe_url/');
        
    return render_to_response('project/safe_url.html',
        {'project':pro, 'su':su,'email':email, },
        context_instance=RequestContext(request)) 

#-------------------------------------------------------------------------------
# For the window jump out to chose artist to new project.
#-------------------------------------------------------------------------------
@login_required
def select_artist(request):
    current_cat, o_tool, o_skill, o_tag = None, [], [], []
    o_cat, old_cat = set([]), set([])
    skts = get_all_cat_skill_tool_tag()
    scroll = ''
    
    if request.GET.has_key('scroll'):
        scroll = request.GET['scroll']

    if request.GET.has_key('c'): # The now visiting category.
        temp = Category.objects.filter(id = request.GET['c'])
        if temp:
            current_cat = temp[0]

    artists, temp_art = User.objects.filter(Q(user_permissions__codename = 'is_artist')), []

    for x in range(0, 100):
        if request.GET.has_key('cat' + str(x)):
            old_cat.add(int(request.GET['cat' + str(x)]))
            tools = [z.id for z in Tool.objects.filter(category__id = request.GET['cat' + str(x)])]
            skills = [z.id for z in Skill.objects.filter(category__id = request.GET['cat' + str(x)])]
            temp1 = set([])
            for y in Tool_user.objects.all():
                if y.tool.id in tools:
                    temp1.add(y.user)
            for y in Skill_user.objects.all():
                if y.skill.id in skills:
                    temp1.add(y.user)            
            temp_art.append(temp1)
        if request.GET.has_key('t' + str(x)):
            tool = Tool.objects.get(id = request.GET['t' + str(x)])
            o_tool.append(tool.id)
            o_cat.add(tool.category.id)
            temp_art.append([y.user for y in Tool_user.objects.filter(tool__id = tool.id)])

        if request.GET.has_key('s' + str(x)):
            skill = Skill.objects.get(id = request.GET['s' + str(x)])
            o_skill.append(skill.id)
            o_cat.add(skill.category.id)
            temp_art.append([y.user for y in Skill_user.objects.filter(skill__id = skill.id)])

        if request.GET.has_key('tag' + str(x)):
            tag = Tag.objects.get(id = request.GET['tag' + str(x)])
            o_tag.append(tag.id)
            o_cat.add(tag.category.id)
            temp_art.append([y.user for y in Tag_user.objects.filter(tag__id = tag.id)])

    if temp_art: # first get artists belong to each tags, and select the common artists.
        artists = [x for x in temp_art[0]]
        for x in temp_art[0]:
            for i in range(1, len(temp_art)):
                if x not in temp_art[i]:
                    artists.remove(x)
                    break

    return render_to_response('project/select_artist.html',
        {'skts':skts, 'category':current_cat, 'artists':artists,
         'old_tools':o_tool, 'old_skills':o_skill, 'old_tags':o_tag,
         'old_cats':o_cat,'old_categories':old_cat,
         'scroll':scroll, },
        context_instance = RequestContext(request))

#-------------------------------------------------------------------------------
# Search the project (title and description).
#-------------------------------------------------------------------------------
@login_required
def search(request):
    if request.method == 'POST':
        pass
    elif request.method == 'GET':
        projects, _projects = [x for x in Project.objects.all()], []
        kw = ''
        if request.GET.has_key('key'):
            kw = request.GET['key']
        
        kw = kw.lower()
        keys = kw.split(' ')
        if len(keys) == 0:
            _projects = projects
        else:
            for key in keys:
                _projects, projects = append_non_repeat(_projects, projects,
#                        [x for x in projects if x.name.lower().find(key.replace('*', '')) > -1])
                        [x for x in projects if x.name.lower().find(key) > -1])
                _projects, projects = append_non_repeat(_projects, projects,
#                        [x for x in projects if x.description.lower().find(key.replace('*', '')) > -1])
                        [x for x in projects if x.description.lower().find(key) > -1])
                
        __projects = split_into_pages(request, _projects)
        return render_to_response('project/search.html', 
                                  {'projects':__projects,'keyword':kw,}, 
                                  context_instance = RequestContext(request))
    return render_to_response('project/search.html', 
                                  {}, 
                                  context_instance = RequestContext(request))
